#pragma once

#include <string_view>
#include <functional>
#include <sstream>

#include "util/logger/logger.h"
#include "preference-convert.h"


namespace PreferenceEntryHelper
{

void addPreferenceCenterAfterLoadCallback(
    const std::string &name,
    std::function<void(const PreferenceRawData &data)> &&callback);

} // namespace PreferenceEntryHelper

template <typename T>
class PreferenceEntry
{
public:
    PreferenceEntry(const std::string_view &name, const T &defaultValue = T())
        : name_(name)
        , value_(defaultValue) {
        
        PreferenceEntryHelper::addPreferenceCenterAfterLoadCallback(name_, [this](const PreferenceRawData &data) {
            if (initialized_) {
                return;
            }
            data >> value_;
            initialized_ = true;
            LOGI << "PreferenceEntry initialized, name: [" << name_ << "], value: [" << value_ << "]";
        });

        LOGI << "PreferenceEntry constructed, name: [" << name_ << "], default: [" << value_ << "]";
    }

    const T &operator*() const {
        return value_;
    }

    const T *operator->() const {
        return &value_;
    }

private:
    const std::string name_;
    bool initialized_ = false;
    T value_;
};

